import { createRouter, createWebHistory } from 'vue-router'
import { useUserStore } from '@/stores'

import NProgress from 'nprogress'
import 'nprogress/nprogress.css'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    { path: '/login', component: () => import('@/views/Login/index.vue') },
    {
      path: '/',
      redirect: '/home',
      component: () => import('@/views/Layout/index.vue'),
      children: [
        {
          path: '/home',
          component: () => import('@/views/Home/index.vue'),
          meta: { title: '首页' }
        },
        {
          path: '/article',
          component: () => import('@/views/Article/index.vue'),
          meta: { title: '健康百科' }
        },
        {
          path: '/notify',
          component: () => import('@/views/Notify/index.vue'),
          meta: { title: '消息中心' }
        },
        {
          path: '/user',
          component: () => import('@/views/User/index.vue'),
          meta: { title: '我的' }
        },
        {
          path: '/user/patient',
          component: () => import('@/views/User/PatientPage.vue'),
          meta: { title: '家庭档案' }
        }
      ]
    }
  ]
})

/**
 * 访问权限控制
 */
const wihteList: Array<string> = ['/login', '/register']

router.beforeEach(() => {
  NProgress.start()
})

router.beforeEach((to) => {
  const userStore = useUserStore()
  if (!userStore.user?.token && !wihteList.includes(to.path)) {
    return { path: '/login' }
  }
})

/**
 * 页面标题
 */
router.afterEach((to) => {
  document.title = `${(to.meta.title as string) || ''}-优医问诊`
})
router.afterEach(() => {
  NProgress.done()
})

/**
 * 修改颜色配置，去掉右上角的圆圈
 */
NProgress.configure({
  showSpinner: false
})
export default router
